package com.nerins.udp.server;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

public class RBACResponseDecoder extends CumulativeProtocolDecoder {

	protected boolean doDecode(IoSession session, IoBuffer in,
			ProtocolDecoderOutput out) throws Exception {

		int intSize = Integer.SIZE / 8;

		int responseType;
		int responseVersion;
		int requestIdLen;
		String requestId;
		int responseContentLen;
		String responseContent;

		if (in.remaining() >= intSize) {
			responseType = in.getInt();
		} else
			return false;

		if (in.remaining() >= intSize) {
			responseVersion = in.getInt();
		} else
			return false;

		if (in.remaining() >= intSize) {
			requestIdLen = in.getInt();
		} else
			return false;

		if (in.remaining() >= requestIdLen) {
			byte[] buf = new byte[requestIdLen];
			in.get(buf);
			requestId = new String(buf, "ISO-8859-1");
		} else
			return false;

		if (in.remaining() >= intSize) {
			responseContentLen = in.getInt();
		} else
			return false;

		if (in.remaining() == responseContentLen) {
			byte[] buf = new byte[responseContentLen];
			in.get(buf);
			responseContent = new String(buf, "ISO-8859-1");
		} else
			return false;

		RBACRequest request = new RBACRequest(responseType, responseVersion,
				requestId, responseContent);

		out.write(request);

		return true;
	}
}